﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Text;

public partial class CheckIn : SessionControlBase
{
    #region internal variables
    public string pacientID
    {
        get { return (string)(this.ViewState["pacientID"] ?? ""); }
        set { this.ViewState["pacientID"] = value; }
    }

    public string presentationID
    {
        get { return (string)(this.ViewState["presentationID"] ?? ""); }
        set { this.ViewState["presentationID"] = value; }
    }

    public string checkinID
    {
        get { return (string)(this.ViewState["checkinID"] ?? ""); }
        set { this.ViewState["checkinID"] = value; }
    }
    
    string intCodeID = null;
    string strAction = "";
    int iTransfers = 1;

    object pacid;
    string checkupType = "";
    string checkinType = "";
    string co_cuDate = "";

    object iCIDiag2 = null;

    bool bRefIDNotUnique = false;

    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //string js = "initialize(event)";
            //ScriptManager.RegisterStartupScript(this, typeof(CheckIn), "initialize", js, true);

            drawDRG_Alphabet();

            if (!IsPostBack)
            {
                //InitializeInternalData();
                OrganizeControls();
                pacientID = (Request.QueryString["pacientID"] ?? "").ToString();
                if (Request.QueryString["checkinID"] != null)
                    checkinID = Request.QueryString["checkinID"].ToString();
            }
        }
        catch (Exception ex)
        {
            debugOutput.Text = ex.ToString();
            throw;
        }
    }

    private void drawDRG_Alphabet()
    {
        StringBuilder sb = new StringBuilder();
        char alphaStart = Char.Parse("A");
        char alphaEnd = Char.Parse("Z");
        string anchorLetter = "";
        LinkButton lnk;

        for (char i = alphaStart; i <= alphaEnd; i++)
        {
            lnk = new LinkButton();
            anchorLetter = i.ToString() + "|";
            lnk.ID = lnk + i.ToString();
            lnk.Text = anchorLetter;
            lnk.CommandArgument = anchorLetter.Replace("|", "");
            lnk.Click +=new EventHandler(lnk_Click);
            lnk.CssClass = "redFontA";
            plcDRGAlphabetic.Controls.Add(lnk);
        }
    }

    protected void lnk_Click(object sender, EventArgs e)
    {
        mdlPopupDiagnostics.Show();
        LinkButton lnk = sender as LinkButton;

        DataSet ds_DRGLimitDate = Hipocrate.DB.DBConnection.GetData("select VALUE from sysconf where code = 'DRG51_LimitDate'");
        DataView dv_DRGLimitDate = ds_DRGLimitDate.Tables[0].DefaultView;

        string querySQL = @"select id, Code, MuresanCode, [Description], Type from vDRG_DiagnosisFull where 1=1 and ( [Code] LIKE '" + lnk.CommandArgument + "%')" +
        @"and( ( convert(smalldatetime,'" + sCIDate.Text +
        @"',103) >= convert(smalldatetime,'" + ds_DRGLimitDate.Tables[0].Rows[0]["VALUE"].ToString() +
        @"',103) and NewType=1) OR ( convert(smalldatetime,'" + sCIDate.Text +
        @"',103) < convert(smalldatetime,'" + ds_DRGLimitDate.Tables[0].Rows[0]["VALUE"].ToString() +
        @"',103) and NewType=0)) order by className, subclassName, code,[Description] ";

        DataSet ds_Diagnostic = Hipocrate.DB.DBConnection.GetData(querySQL);
        DataView dv_Diagnostic = ds_Diagnostic.Tables[0].DefaultView;

        rptResultsDiagnostic.DataSource = dv_Diagnostic;
        rptResultsDiagnostic.DataBind();
    }

    private void InitializeInternalData()
    {
        int temp;
        if (Request.QueryString["checkinID"] != null)
        {
            checkinID = Request.QueryString["checkinID"];
            intCodeID = Request.QueryString["checkinID"];
        }
        else if (Request.QueryString["id"] != null)
        {
            checkinID = Request.QueryString["id"];
            intCodeID = Request.QueryString["id"];
        }
        strAction = Request.QueryString["action"] ?? ""; // hdnAction
        if (strAction == "" || strAction == "undefined")
        {
            strAction = "L";
            var dt = DateTime.Now;
            sCIDate.Text = dt.ToString("dd/MM/yyyy");
            sCITime.Text = dt.ToString("HH:mm");
        }

        if (intCodeID != null)
        {
            DataSet ds = Hipocrate.DB.DBConnection.GetData("SELECT PacientID FROM checkins WHERE ID=" + intCodeID);
            if (ds.Tables[0].Rows.Count > 0)
                pacid = ds.Tables[0].Rows[0]["PacientID"];

            ds = Hipocrate.DB.DBConnection.GetData("select top 1 ci.CIDiag2, CONVERT(VARCHAR(10), CUDate, 103) sCUDate, CONVERT(VARCHAR(5), DateAdd(mi, +1, CUDate), 108) sCUTime from checkups cu right join checkins ci on cu.ExternalID = ci.ID and cu.ExternalType = 'CI' where ci.ID = " + intCodeID + " order by CUDate desc ");
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow row = ds.Tables[0].Rows[0];
                co_cuDate = row["sCUDate"] + " " + row["sCUTime"];
                if (row["sCUDate"] == DBNull.Value && row["sCUTime"] == DBNull.Value)
                    co_cuDate = "";
                if ((iCIDiag2 == null) || !int.TryParse(iCIDiag2.ToString(), out temp))
                    iCIDiag2 = row["CIDiag2"] ?? "";
            }
        }
    }

    private void OrganizeControls()
    {
        duplicat.Visible = bRefIDNotUnique;
        string sCIType = "";
        DataSet ds = null;
        string sql = @"SELECT id, name, drg_code FROM Checkin_Types
				WHERE active = 1 ";

        sql += " ORDER BY drg_code, name";
        CIType.DataSource = Hipocrate.DB.DBConnection.GetData(sql);
        CIType.DataValueField = "ID";
        CIType.DataTextField = "Name";
        CIType.DataBind();
        CIType.SelectedValue = sCIType;
        sql = "select ID, Name from checkin_criteria where Active=1 ";

        ds = Hipocrate.DB.DBConnection.GetData(sql);
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
        Tools.DataBindDDL(strCheckinCriteria, Tools.AddEmptyRow(ds), "ID", "Name");
        sql = "select s.Code,s.Name from SECTIONS s where s.Active=1";

        ds = Hipocrate.DB.DBConnection.GetData(sql);
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
        Tools.DataBindDDL(sSectionCode, Tools.AddEmptyRow(ds), "Code", "Name"); //Server.HTMLEncode(NE(ds["Name"]))

        sql = "select Name, Code from REGIM_TYPES order by Name";

        ds = Hipocrate.DB.DBConnection.GetData(sql);
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
        Tools.DataBindDDL(sMealCode, Tools.AddEmptyRow(ds), "Code", "Name");

        sql = "select distinct v.Id, v.FullName, us.SectionCode from vUserWhoCanCheckIn v join STAFF_SECTIONS us on v.ID=us.StaffID ";

        ds = Hipocrate.DB.DBConnection.GetData(sql);
        foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
        Tools.DataBindDDL(iCIMedicID, Tools.AddEmptyRow(ds), "Id", "FullName");

        RetrieveRegimTypes();
    }

    private void RetrieveRegimTypes()
    {
        string sql = @"select {0} ID, Name, Code, '' as Display
					from REGIM_TYPES
					{1}
					order by Name";
        DataSet ds = null;
        if (checkupType == (string)Session["CUTYPE_1DAYCI"])
        {
            ds = Hipocrate.DB.DBConnection.GetData(string.Format(sql, "TOP 1", ""));
            DataRow dr = ds.Tables[0].Rows[0];
            dr["ID"] = "2";
            dr["Display"] = "Nu necesita";
        }
        else
        {
            if (iTransfers == 1)
            {
                ds = Hipocrate.DB.DBConnection.GetData(string.Format(sql, "", ""));
                foreach (DataColumn c in ds.Tables[0].Columns) c.AllowDBNull = true;
                ds = Tools.AddEmptyRow(ds);
            }
            else
                ds = Hipocrate.DB.DBConnection.GetData(string.Format(sql, "",
                    "where [ID]=(select MealRegime from checkins where [id]=" + intCodeID + ")"));
            ds.Tables[0].Columns["Display"].ReadOnly = false;
            //foreach (DataRow r in ds.Tables[0].Rows)
            //    if (r["ID"] != DBNull.Value)
            //        r["Display"] = Server.HtmlEncode((r["Name"] ?? "").ToString()) + " (" + r["Code"] + ")";
        }

        Tools.DataBindDDL(sMealCode, ds, "ID", "Display");
        if (Request.Form["sMealCode"] != "undefined")
            sMealCode.SelectedValue = Request.Form["sMealCode"];
    }

    public void LoadData()
    {
        divGeneralitati.Style.Add("display", "block");
        DataSet ds;
        TabbedDetails.ShowUrl(this, "action", TabbedDetails.action[TabbedDetails.checkinTabIndex],
            "pacientID", pacientID, "checkinID", checkinID);

        if (pacientID.Length > 0)
        {
            ds = Hipocrate.DB.DBConnection.GetData(@"SELECT DISTINCT CIID, RefID, sCIDate as sDate, sCITime as sTime, SectionName, MedicFullName, CIDiagnosis as Diagnosis, CIDiagnosisName as DiagnosisName, Cancel, CIDate as Chronology, TransferID, 'Internare' as eType
				FROM vCheckInFull WHERE PacientID = " + pacientID + @"
				ORDER BY Chronology DESC, TransferID DESC");
            int resultSize = ds.Tables[0].Rows.Count;
            for (int tr = 0; tr < resultSize; ++tr)
            {
                if (ds.Tables[0].Rows[tr]["DiagnosisName"].ToString().Length == 0)
                    ds.Tables[0].Rows[tr]["DiagnosisName"] = "necompletat";
                if ((tr > 0) && (ds.Tables[0].Rows[tr]["CIID"].Equals(ds.Tables[0].Rows[tr - 1]["CIID"])))
                    ds.Tables[0].Rows[tr - 1]["eType"] = "Transfer";
            }
            resultsCheckins.DataSource = ds;
            resultsCheckins.DataBind();
            noCheckins.Visible = resultsCheckins.Items.Count == 0;
        }

        if(checkinID.Length == 0)
        {
            ds = Hipocrate.DB.DBConnection.GetData(@"SELECT typeID FROM vCheckupSearch VC
				INNER JOIN Presentations P ON VC.ExternalID=P.ID
				WHERE P.ID = '" + presentationID + "'");
            if (ds.Tables[0].Rows.Count > 0)
                checkupType = ds.Tables[0].Rows[0]["typeID"].ToString();
        }
        else // has id
        {
            ds = Hipocrate.DB.DBConnection.GetData(@"SELECT CI.CIType, CI.coID, DS.Code, CU.typeID
					FROM CHECKINS CI left join presentations pr on pr.checkinid=ci.id  left join checkups cu on cu.externalid=pr.id and externaltype= 'pr' LEFT JOIN CHECKOUTS CO ON CI.COID = CO.COID LEFT JOIN DRG_STATUSES DS ON CO.DRGStatusID = DS.ID
					WHERE CI.ID = '" + checkinID + "'");
            DataRow row = ds.Tables[0].Rows[0];
            checkinType = row["CIType"].ToString();
            checkupType = row["typeID"].ToString();
            bool bCloseCI = false;
            if (checkupType == Session["CUTYPE_1DAYCI"] || checkinType == Session["CITYPE_1DAYCI"])
                bCloseCI = (row["COID"] != null && row["COID"] != DBNull.Value && row["COID"] != "");
            bool bDRGStatus = (row["Code"] == "DAY_F");
        }

        if (intCodeID != null && (checkupType == Session["CUTYPE_1DAYCI"]))
        {
            ds = Hipocrate.DB.DBConnection.GetData(@"select top 1 DateAdd(mi, +1, CUDate) CUDate from checkups cu inner join checkins ci on cu.ExternalID = ci.ID and cu.ExternalType = 'CI'
					where ci.ID = " + intCodeID + " order by CUDate desc ");
            if (ds.Tables[0].Rows.Count > 0)
                co_cuDate = ds.Tables[0].Rows[0]["CUDate"].ToString();

            if (co_cuDate == null)
                co_cuDate = "";
        }

        co_cuDate = "";
        ds = Hipocrate.DB.DBConnection.GetData(@"select * from vCheckInLoad where CIID=" + checkinID);
        DataRow row2 = ds.Tables[0].Rows[0];
        strCheckinCriteria.SelectedValue = row2["CICriteriaID"].ToString();
        sSectionCode.SelectedValue = row2["SectionCode"].ToString();
        sMealCode.SelectedValue = row2["MealCode"].ToString();
        strRefID.Text = row2["RefID"].ToString();
        sCIDate.Text = row2["sCIDate"].ToString();
        sCITime.Text = row2["sCITime"].ToString();
        iCIMedicID.SelectedValue = row2["CIMedicID"].ToString();

        LoadDetailsRequest();

        //string js = "hideShowGeneralInternal()";
        //ScriptManager.RegisterStartupScript(this, typeof(CheckIn), "hideShowGeneralInternal", js, true);

        drpTypeSearch.Items.Clear();
        ListItem lst_B = new ListItem("La inceput", "1");
        ListItem lst_W = new ListItem("Cuvant in diagnostic", "2");
        ListItem lst_D = new ListItem("Tot diagnosticul", "3");

        drpTypeSearch.Items.Insert(0, lst_B);
        drpTypeSearch.Items.Insert(1, lst_W);
        drpTypeSearch.Items.Insert(2, lst_D);
        drpTypeSearch.SelectedIndex = 2;

        drpTypeDiag.Items.Clear();
        ListItem lst_Acut = new ListItem("Acut", "A");
        ListItem lst_Cronic = new ListItem("Cronic", "C");
        ListItem lst_Subacut = new ListItem("Subacut", "S");

        drpTypeDiag.Items.Insert(0, "");
        drpTypeDiag.Items.Insert(1, lst_Acut);
        drpTypeDiag.Items.Insert(2, lst_Cronic);
        drpTypeDiag.Items.Insert(3, lst_Subacut);
    }

    private void LoadDetailsRequest()
    {
        lblDetailsRequest.Text = "Detalii Prezentare: <span class=\"redFontSmall\">(" + getPacient(pacientID) + "[" + pacientID + "])</span>";


        DataSet ds_DetailsPacient = Hipocrate.DB.DBConnection.GetData("select id,firstname, lastname, cnp, GrSang, rh, attention from pacients where [id]=" + pacientID + "");
        DataView dv = ds_DetailsPacient.Tables[0].DefaultView;
        lblPacient.Text = "<span class=\"redFontSmall\">" + getPacient(pacientID) + "[" + pacientID + "]</span>";
        lblCNP.Text = dv[0]["cnp"].ToString();

        string tempGeneral = "";
        if (!string.IsNullOrEmpty(dv[0]["GrSang"].ToString()))
            tempGeneral += dv[0]["GrSang"].ToString();
        if (dv[0]["rh"].ToString() == "1")
            tempGeneral += "RH&nbsp;pozitiv; ";
        else if (dv[0]["rh"].ToString() == "0")
            tempGeneral += "RH&nbsp;negativ; ";

        DataSet ds_DetailsPacientSex = Hipocrate.DB.DBConnection.GetData("select Sex, datediff(Y, GetDate(), BirthDate) as Age, CIID from pacients where [id]=" + pacientID + "");
        DataView dv1 = ds_DetailsPacientSex.Tables[0].DefaultView;

        if (dv1[0]["Sex"].ToString() == "True")
            tempGeneral += "sex&nbsp;masculin;";
        else if (dv1[0]["Sex"].ToString() == "False")
            tempGeneral += "sex&nbsp;feminin; ";
        else
            tempGeneral += "sex&nbsp;nespecificat; ";

        lblGeneral.Text = tempGeneral;

        DataSet ds_DetailsAll = Hipocrate.DB.DBConnection.GetData("select pac.ID as PacID, pac.FirstName, pac.LastName, datediff(yy, pac.BirthDate, getdate()) as Age, pac.BirthDate, pac.CNP, pac.Sex, z.judetnume AS Zone, pac.GrSang, prof.Description as ProfName, pac.Workplace, pac.RH, pac.Attention, pac.Alergies, p.ID as PresID, convert(varchar(10), p.DeclaredDate, 103) as PresDate, convert(varchar(5), p.DeclaredDate, 108) as PresTime, s.Code as SecCode, s.Name as SecName, st.Id as StaffId, st.LastName + ' ' + st.FirstName as MedicName, send.Description as SendDesc, p.SenderName, p.SenderClinicName, p.SenderObs, p.CheckInID, p.Emergency, Insurers.Code as InsurerCode from (Pacients pac left join Professions prof on pac.ProfessionId = prof.Id) inner join Presentations p on p.PacientID = pac.Id inner join Sections s on p.SectionId = s.Code inner join Staff st on p.DoctorId = st.Id left join Insurers on p.InsurerId = Insurers.Id left join SenderTypes send on p.SenderTypeId = send.Id left join drg_city c inner join drg_districts z on z.id=c.localitatejudet_id on p.ZoneID = c.Id where p.Id=" + getPrezentare(checkinID) + "");
        DataView dv2 = ds_DetailsAll.Tables[0].DefaultView;

        lblAsigurat.Text = dv2[0]["InsurerCode"].ToString();
        lblProfesie.Text = dv2[0]["ProfName"].ToString();
        lblAlergii.Text = dv2[0]["Alergies"].ToString();

        lblFisa.Text = "<span class=\"redFontSmall\"> Fisa de prezentare[" + getPrezentare(checkinID) + "]</span>";
        lblDate.Text = dv2[0]["PresDate"].ToString() + " " + dv2[0]["PresTime"].ToString();
        lblSection.Text = dv2[0]["SecName"].ToString();
        lblMedic.Text = dv2[0]["MedicName"].ToString();
        if (dv2[0]["Emergency"].ToString() == "True")
            lblUrgenta.Text = "DA";
        else lblUrgenta.Text = "NU";

        string externare = getExternare(checkinID);
        if (externare != "")
            lblExternat.Text = "<span class=\"redFontSmall\"> Fisa de externare[" + externare + "]</span>";

    }

    protected string getPacient(string pacient)
    {
        DataSet ds_Pacient = Hipocrate.DB.DBConnection.GetData("select firstname, lastname from pacients where [id]=" + pacient);
        DataView dv = ds_Pacient.Tables[0].DefaultView;

        return dv[0]["lastName"].ToString() + " " + dv[0]["firstName"].ToString();
    }

    protected string getPrezentare(string internare)
    {
        DataSet ds_Prezentare = Hipocrate.DB.DBConnection.GetData("select id from presentations where [checkinid]=" + internare);
        DataView dv = ds_Prezentare.Tables[0].DefaultView;

        return dv[0]["id"].ToString();
    }

    protected string getExternare(string internare)
    {
        DataSet ds_Prezentare = Hipocrate.DB.DBConnection.GetData("select coid from checkins where [id]=" + internare);
        DataView dv = ds_Prezentare.Tables[0].DefaultView;

        return dv[0]["coid"].ToString();
    }

    protected void detaliiPacient_Click(object sender, EventArgs e)
    {
        LinkButton b = sender as LinkButton;
        System.Web.UI.Control c = this.Parent;
        while ((c != null) && !(c is TabContainer))
            c = c.Parent;
        TabContainer container = c as TabContainer;
        if (container == null)
            return;

        container.ActiveTabIndex = TabbedDetails.pacientTabIndex;
    }

    protected void detaliiFisa_Click(object sender, EventArgs e)
    {
        LinkButton b = sender as LinkButton;
        System.Web.UI.Control c = this.Parent;
        while ((c != null) && !(c is TabContainer))
            c = c.Parent;
        TabContainer container = c as TabContainer;
        if (container == null)
            return;

        container.ActiveTabIndex = TabbedDetails.admissionTabIndex;
    }

    protected void detaliiFisaExternat_Click(object sender, EventArgs e)
    {
        LinkButton b = sender as LinkButton;
        System.Web.UI.Control c = this.Parent;
        while ((c != null) && !(c is TabContainer))
            c = c.Parent;
        TabContainer container = c as TabContainer;
        if (container == null)
            return;

        container.ActiveTabIndex = TabbedDetails.checkoutTabIndex;
    }

    protected void resultsCheckins_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //TODO
    }

    protected void checkinID_Click(object sender, EventArgs e)
    {
        //TODO
    }

    protected void imgDiagnostic_Click(object sender, EventArgs e)
    {
        try
        {
            mdlPopupDiagnostics.Show();

            DataSet ds_DRGLimitDate = Hipocrate.DB.DBConnection.GetData("select VALUE from sysconf where code = 'DRG51_LimitDate'");
            DataView dv_DRGLimitDate = ds_DRGLimitDate.Tables[0].DefaultView;

            string querySQL = @"select ID, Code, MuresanCode, Description, Type from vDRG_DiagnosisFull 
            where type=1 and( ( convert(smalldatetime,'" + sCIDate.Text + 
            @"',103) >= convert(smalldatetime,'" + ds_DRGLimitDate.Tables[0].Rows[0]["VALUE"].ToString() + 
            @"',103) and NewType=1) OR ( convert(smalldatetime,'" + sCIDate.Text + 
            @"',103) < convert(smalldatetime,'" + ds_DRGLimitDate.Tables[0].Rows[0]["VALUE"].ToString() + 
            @"',103) and NewType=0)) order by className, subclassName, code,[Description] ";

            DataSet ds_Diagnostic = Hipocrate.DB.DBConnection.GetData(querySQL);
            DataView dv_Diagnostic = ds_Diagnostic.Tables[0].DefaultView;

            rptResultsDiagnostic.DataSource = dv_Diagnostic;
            rptResultsDiagnostic.DataBind();

        }
        catch (Exception ex)
        {
            this.SetMessage(ex.Message, true);
        }
    }

    protected void rptDiagnostic_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Footer) || (e.Item.ItemType == ListItemType.Header))
            return;
        DataRowView row = e.Item.DataItem as DataRowView;
        string cmdArg = (row["Description"]).ToString();

        foreach (Control c in e.Item.Controls)
        {
            if (c is LinkButton)
                (c as LinkButton).CommandArgument = cmdArg;
        }
    }

    protected void SelectDiagnostic(object sender, EventArgs e)
    {
        mdlPopupDiagnostics.Hide();

        if (sender != null)
        {
            LinkButton lnk = sender as LinkButton;
            string[] info = lnk.CommandArgument.ToString().Split(';');
        }
    }

    protected void btnSearchDRG_Click(object sender, EventArgs e)
    {
        
    }
}
